"""
Video2Text 后端主程序

Author: Video2Text Team
Date: 2024-03-20
"""
from typing import Dict
from fastapi import FastAPI, HTTPException, UploadFile, File
from pydantic import BaseModel
from fastapi.middleware.cors import CORSMiddleware
from .services.audio_service import AudioService
from .services.text_optimizer_service import TextOptimizerService
import logging

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

app = FastAPI(title="Video2Text API")
audio_service = AudioService()
text_optimizer = TextOptimizerService()

# 定义请求模型
class TextOptimizeRequest(BaseModel):
    text: str

# 配置CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["chrome-extension://*"],  # 允许Chrome扩展访问
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

@app.post("/api/v1/audio/process")
async def process_audio(audio: UploadFile = File(...)):
    """
    处理音频数据接口
    
    Args:
        audio: 上传的音频文件
        
    Returns:
        Dict: 包含处理结果的字典
    """
    try:
        logger.info(f"收到音频文件: {audio.filename}, content_type: {audio.content_type}")
        
        # 读取音频数据
        audio_data = await audio.read()
        logger.info(f"音频数据大小: {len(audio_data)} bytes")
        
        # 处理音频
        result = await audio_service.process_audio(audio_data)
        
        if result is None:
            logger.error("音频处理失败")
            raise HTTPException(
                status_code=500, 
                detail={
                    "message": "音频处理失败",
                    "code": "AUDIO_PROCESS_ERROR"
                }
            )
            
        logger.info("音频处理成功")
        return {
            "status": "success",
            "text": result
        }
        
    except Exception as e:
        logger.error(f"处理异常: {str(e)}", exc_info=True)
        raise HTTPException(
            status_code=500,
            detail={
                "message": str(e),
                "code": "INTERNAL_ERROR"
            }
        )

@app.get("/api/v1/health")
async def health_check():
    """健康检查接口"""
    return {"status": "healthy"}

@app.post("/api/v1/text/optimize")
async def optimize_text(request: TextOptimizeRequest):
    """文本优化接口
    
    对输入文本进行阅读性优化，包括:
    1. 段落拆分
    2. 标题体系构建
    """
    result = await text_optimizer.optimize_text(request.text)
    return {
        "status": "success",
        "data": result
    } 